﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;

namespace UniRlv.UI.Main.ManufactureManage
{
    public partial class FrmAddOrEditTask : UniRlv.UI.Main.DialogBase
    {
        List<ProductInfo> listProducts;
        List<ProductionLine> listLines;
        ProductInfo curProduct = null;
        ProductionLine curLine = null;
        ProductionTask task = null;

        public ProductionTask Task
        {
            get { return task; }
            set { task = value; }
        }

        public BindingList<PrintInfo> PrintInfos { get; set; }
        

        public FrmAddOrEditTask()
        {
            InitializeComponent();

            PrintInfos = new BindingList<PrintInfo>();
        }

        private void FrmAddOrEditTask_Load(object sender, EventArgs e)
        {
            #region 初始化产品列表

            Wait();
            string msg = string.Empty;
            listProducts = DALOpr.QueryAll<ProductInfo>(ref msg);

            if (!string.IsNullOrEmpty(msg))
            {
                ShowErrorMessageBox("出现错误", msg);
                Close();
                return;
            }
            else
            {
                if (listProducts == null || listProducts.Count == 0)
                {
                    ShowErrorMessageBox("提示", "缺少产品信息");
                    Close();
                    return;
                }
                else
                {
                    foreach (var item in listProducts)
                    {
                        lstProduct.Items.Add(item.ToString());
                    }
                        
                    
                }

            }

            #endregion

            #region 初始化产线列表

            msg = string.Empty;
            listLines = DALOpr.QueryAll<ProductionLine>(ref msg);

            if (!string.IsNullOrEmpty(msg))
            {
                ShowErrorMessageBox("出现错误", msg);
                Close();
                return;

            }
            else
            {
                if (listLines == null || listLines.Count == 0)
                {
                    ShowErrorMessageBox("提示", "缺少产线信息");
                    Close();
                    return;
                }
                else
                {
                    foreach (var item in listLines)
                    {
                        lstLine.Items.Add(item.ToString());
                    }
                    
                }

            }

            

            #endregion

            #region 初始化其他控件
            UIHelper.BindingComboBox2Setting(lstMinPackUnit, "unit", "，");
            UIHelper.BindingComboBox2Setting(lstMinTagUnit, "unit", "，");

            #endregion

            if (task != null)
            {
                msg = string.Empty;

                string sql = "select * from ProductInfo where id=" + task.productID;
                curProduct = DALOpr.QuerySingle<ProductInfo>(sql, ref msg);

                if (curProduct == null)
                {
                    ShowInfoMessageBox("提示", "产品信息已经删除，无法编辑该任务");
                    Close();
                    return;
                }
                msg = string.Empty;
                sql = "select * from ProductionLine where id=" + task.lineID;

                curLine = DALOpr.QuerySingle<ProductionLine>(sql, ref msg);

                lstProduct.SelectedIndex = listProducts.IndexOf(curProduct);
                lstLine.SelectedIndex = listLines.IndexOf(curLine);
                lstProduct.Enabled = false;//修改任务，不允许变更产品信息
                txtBatch.Text = task.batch;
                txtRemark.Text = task.remarks;
                lstGG.Text = task.gg;
                lstMinPackUnit.Text = task.minPackUnit;
                lstMinTagUnit.Text = task.minTagUnit;
                txtMinTagGG.Text = task.minTagGG;
                txtTagRatio.Text = task.tagRatio;
                numTagPackRatio.Value = task.tagPackRatio;
                numPlanQty.Value = task.planQuantity;
                dtpProduce.Value = task.produceDate;
                dtpOperate.Value = task.operateDate;
                txtNumber.Text = task.number;
                txtSrcCheckPath.Text = task.extendInfo;
                txtCreator.Text = task.creator;
                txtResponser.Text = task.responser;
            }
            else
            {
                PrintInfos = new BindingList<PrintInfo>();
                lstProduct.SelectedIndex = 0;
                lstLine.SelectedIndex = 0;
                txtCreator.Text = PublicObject.CurUser.name;
                txtResponser.Text = PublicObject.CurUser.name;
            }

            UIHelper.InitDataGridView(dgvPrintInfo);
            dgvPrintInfo.DataSource = PrintInfos;

            if (ConfigurationHelper.AppGetInt("dupCheckType") == 0)
            {
                btnCheckSrcPath.Enabled = false;
            }

            WaitBack();
        }

        #region 控件事件响应
        private void chkTagRatio_CheckedChanged(object sender, EventArgs e)
        {
            txtTagRatio.ReadOnly = !chkTagRatio.Checked;
        }

        private void chkOperate_CheckedChanged(object sender, EventArgs e)
        {
            dtpOperate.Enabled = chkOperate.Checked;
        }

        private void lstProductInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            curProduct = null;
            foreach (var item in listProducts)
            {
                if (item.ToString().Equals(lstProduct.Text))
                {
                    curProduct = item;
                    break;
                }
            }

            if (curProduct == null)
            {
                ShowErrorMessageBox("出现错误", "无法查询到所选产品！");
                return;
            }

            lstGG.Items.Clear();
            lstGG.Items.AddRange(AppHelper.GetGG(curProduct.gg));
            txtNumber.Text = curProduct.itemid;

            if (lstGG.Items.Count>0)
            {
                if (task == null)
                {
                    lstGG.SelectedIndex = 0;
                }
                else
                {
                    lstGG.Text = task.gg;
                    lstGG_SelectedIndexChanged(null, null);//如果刚好两个产品的规格都样，主动调用lstGG_SelectedIndexChanged才能触发包装信息刷新
                }

                
            }

            dtpProduce_ValueChanged(null, null);
        }

        private void lstGG_SelectedIndexChanged(object sender, EventArgs e)
        {
            string msg = string.Empty;

            Wait();

            List<PackageRule> rules = DALOpr.Query<PackageRule>("productID = " + curProduct.ID, ref msg);

            if (string.IsNullOrEmpty(msg))
            {
                if (rules != null && rules.Count>0)
                {
                    foreach (var item in rules)
                    {
                        if (item.gg.Equals(lstGG.Text, StringComparison.OrdinalIgnoreCase))
                        {//产品信息、规格一致
                            ShowInfo(curProduct, item);
                            WaitBack();
                            return;
                        }
                    }

                    ShowInfo(curProduct, rules[0]);
                }
                else
                {
                    ShowInfo(curProduct, null);

                    if (task == null)
                    {
                        chkTagRatio.Checked = true;
                        ShowWarnMessageBox("提示", "产品的该规格无包装信息，当前显示为默认包装");
                    }
                }
            }
            else
            {
                ShowErrorMessageBox("出现错误", msg);
            }

            WaitBack();
        }

        private void btnPrinterAdd_Click(object sender, EventArgs e)
        {
            FrmSelectPrinter frm = new FrmSelectPrinter();
            frm.Text = "添加打印机";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (IfContainsPrintInfo(PrintInfos, frm.Tag as PrintInfo))
                {
                    ShowWarnMessageBox("警告", "不能为同一工位号和子号重复添加打印信息");
                }
                else
                {
                    PrintInfos.Add(frm.Tag as PrintInfo);
                }
               
            }
        }

        private bool IfContainsPrintInfo( IEnumerable<PrintInfo> pis, PrintInfo pi)
        {
            foreach (var item in pis)
            {
                if (item.StationNum == pi.StationNum && item.SubDeviceNum == pi.SubDeviceNum)
                {
                    return true;
                }
            }

            return false;
        }

        private void btnPrinterDel_Click(object sender, EventArgs e)
        {
            if (dgvPrintInfo.CurrentRow != null)
            {
                PrintInfo p = dgvPrintInfo.CurrentRow.DataBoundItem as PrintInfo;

                if(MessageBox.Show(this, "确认删除以下打印信息？\r\n" + p.ToString(), "请确认",  MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    PrintInfos.Remove(p);
                }
            }
            else
            {
                ShowWarnMessageBox("提示", "先选择删除的打印机！");
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (curProduct == null)
            {
                ShowWarnMessageBox("提示", "未选中产品！");
                lstProduct.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtBatch.Text))
            {
                ShowWarnMessageBox("提示", "批次号不能为空！");
                txtBatch.Focus();
                return;
            }

            if (string.IsNullOrEmpty(lstGG.Text))
            {
                ShowWarnMessageBox("提示", "规格不能为空");
                lstGG.Focus();
                return;
            }

            if (!AppHelper.IsGoodRatio(txtTagRatio.Text))
            {
                ShowWarnMessageBox("提示", "包装比例非法，请重新修改");
                chkTagRatio.Checked = true;
                txtTagRatio.Focus();
                return;
            }

            if (string.IsNullOrEmpty(lstMinPackUnit.Text))
            {
                ShowWarnMessageBox("提示", "最小包装单位不能为空");
                lstMinPackUnit.Focus();
                return;
            }

            if (string.IsNullOrEmpty(lstMinTagUnit.Text))
            {
                ShowWarnMessageBox("提示", "最小贴码单位不能为空");
                lstMinTagUnit.Focus();
                return;
            }


            if (task == null)
            {//add
                task = new ProductionTask();

                //插入默认元素
                task.ID = DALOpr.GetNextObjectID("ProductionTask");
                task.createTime = DateTime.Now;
                task.creator = txtCreator.Text;
                task.responser = txtResponser.Text;
                task.state = (int)task_state.TS_NEW;
            }

            task.number = txtNumber.Text;
            task.batch = txtBatch.Text;
            task.company = PublicObject.CurCompany.name;
            task.exportTimes = 0;
            task.gg = lstGG.Text;
            task.lineID = listLines[lstLine.SelectedIndex].ID;
            task.minPackUnit = lstMinPackUnit.Text;
            task.minTagUnit = lstMinTagUnit.Text;
            task.minTagGG = txtMinTagGG.Text;
            task.oprator = PublicObject.CurCompany.userName;
            task.packageState = (int)package_state.PS_NORMAL;
            task.planQuantity = Convert.ToInt32(numPlanQty.Value);
            task.produceDate = dtpProduce.Value;
            task.productID = curProduct.ID;
            task.pzwh = curProduct.pzwh;
            task.remarks = txtRemark.Text;
            task.scanQuantity = 0;
            task.tagLevel = AppHelper.GetTagLevel(txtTagRatio.Text);
            task.tagPackRatio = Convert.ToInt32(numTagPackRatio.Value);
            task.tagRatio = txtTagRatio.Text;
            task.tym = curProduct.tym;
            task.workshopName = listLines[lstLine.SelectedIndex].ToString();
            task.yxq = dtpYQW.Value;
            task.spm = curProduct.spm;
            task.operateDate = dtpOperate.Value;
            task.extendInfo = txtSrcCheckPath.Text;

            foreach (var item in PrintInfos)
            {
                item.TaskID = task.ID;
            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            Close();
        }

        private void dtpProduce_ValueChanged(object sender, EventArgs e)
        {
            dtpYQW.Value = AppHelper.SYZSGetYXQ(dtpProduce.Value, (date_unit)curProduct.yxqdw, curProduct.yxq);
        }

        #endregion

        private void ShowInfo(ProductInfo p, PackageRule r)
        {
            if (r == null)
            {
                numTagPackRatio.Value = task == null ? 1 : task.tagPackRatio;
                txtTagRatio.Text = task == null ? "1:?" : task.tagRatio;
                lstMinPackUnit.Text = task == null ? "" : task.minPackUnit;
                lstMinTagUnit.Text = task == null ? "" : task.minTagUnit;
                txtMinTagGG.Text = "";
            }
            else
            {
                numTagPackRatio.Value = r.tagPackRatio;
                txtTagRatio.Text = r.tagRatio;
                lstMinPackUnit.Text = r.minPackUnit;
                lstMinTagUnit.Text = r.minTagUnit;
                txtMinTagGG.Text = r.minTagGG;
            }

        }

        private void lstProduct_TextUpdate(object sender, EventArgs e)
        {
            //清空combobox
            lstProduct.Items.Clear();

            //遍历全部备查数据
            foreach (ProductInfo item in listProducts)
            {

                if (string.IsNullOrEmpty(lstProduct.Text))
                {//空，包含全部
                    lstProduct.Items.Add(item.ToString());
                }
                else
                {
                    if (item.ToString().Contains(lstProduct.Text))
                    {
                        //符合，插入ListNew
                        lstProduct.Items.Add(item.ToString());
                    }
                }
            }

            if (lstProduct.Items.Count == 0)
            {
                lstProduct.SelectionStart = lstProduct.Text.Length;
                return;
            }

            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            lstProduct.SelectionStart = lstProduct.Text.Length;
            //保持鼠标指针原来状态，有时候鼠标指针会被下拉框覆盖，所以要进行一次设置。
            Cursor = Cursors.Default;
            //自动弹出下拉框
            lstProduct.DroppedDown = true;
        }

        private void btnPrinterEdit_Click(object sender, EventArgs e)
        {

            if (dgvPrintInfo.CurrentRow != null)
            {
                PrintInfo p = dgvPrintInfo.CurrentRow.DataBoundItem as PrintInfo;

                FrmSelectPrinter frm = new FrmSelectPrinter();
                frm.Text = "修改打印机";
                frm.Tag = p;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    int idx = PrintInfos.IndexOf(p);

                    if (p.StationNum!=(frm.Tag as PrintInfo).StationNum && p.SubDeviceNum != (frm.Tag as PrintInfo).SubDeviceNum)
                    {
                        ShowWarnMessageBox("警告", "不能修改打印信息的工位号和子号，如需修改请先删除后添加");
                        return;
                    }

                    PrintInfos.RemoveAt(idx);
                    PrintInfos.Insert(idx, frm.Tag as PrintInfo);
                }
            }
            else
            {
                ShowWarnMessageBox("提示", "先选择修改的打印机！");
            }
        }

        private void dgvPrintInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            btnPrinterEdit.PerformClick();
        }

        private void btnPick_Click(object sender, EventArgs e)
        {
            FrmSelectPrintInfo frm = new FrmSelectPrintInfo();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (IfContainsPrintInfo(PrintInfos, frm.Tag as PrintInfo))
                {
                    ShowWarnMessageBox("警告", "不能为同一工位号和子号重复添加打印信息");
                }
                else
                {
                    PrintInfos.Add(frm.Tag as PrintInfo);
                }
                
            }
        }

        private void lstProduct_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
            {
                return;
            }
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(lstProduct.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 5);
        }

        private void btnCheckSrcPath_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)文本文件|*.txt|(*.*)所有文件|*.*";
            ofd.FileName = txtSrcCheckPath.Text;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtSrcCheckPath.Text = ofd.FileName;
            }
        }
    }
}
